<template>
  <div class="tab_container">
    <div class="list_item">
      <div class="list_item_left">
        <div class="list_item_title">
          <span style="margin-right: 8px;">调试模式</span>
          <RadioGroup v-model="currentType"
                      type="button"
                      button-style="solid"
                      size="small"
                      @on-change="changeDebugType">
            <Radio v-for="(item, index) in debugTypes"
                   :key="index"
                   :label="item.name">{{item.label}}</Radio>
          </RadioGroup>
        </div>
        <div class="list_item_desc">
          <Button v-if="currentType == 'file'"
                  @click="chooseBBCFile">选择文件</Button>
          <Input :value="currentType == 'file' ? pluginInfo.local : (pluginInfo.debug.path || debugTypes[currentIndex].defaultValue)"
                 :placeholder="debugTypes[currentIndex].placeholder"
                 @on-change="changeIndexPath"></Input>
        </div>
        <transition name="fade">
          <div class="list_item_tip">修改调试模式后，请点击 重载。</div>
        </transition>
      </div>
      <div class="list_item_right">
        <transition name="fade">
          <a href="javascript:void(0)"
             @click="reloadPlugin">重载</a>
        </transition>
      </div>
    </div>
    <div class="list_item">
      <div class="list_item_left">
        <div class="list_item_title">
          打包
        </div>
        <div class="list_item_desc2">
          <div>打包目录: {{rootPath}}</div>
          <transition name="fade">
            <div v-if="showPackInfo"><a href="javascript:void(0)"
                 v-text="packInfo[pluginInfo.id].path.split(SEP).pop()"
                 style="margin-right: 4px;"
                 @click="openPack"></a>最后打包于: <a href="javascript:void(0)"
                 @click="noop"
                 v-text="$timeFormat2(packInfo[pluginInfo.id].createAt)"></a>, 大小: <a href="javascript:void(0)"
                 @click="noop"
                 v-text="$sizeFormat(packInfo[pluginInfo.id].size)"></a></div>
          </transition>
        </div>
      </div>
      <div class="list_item_right">
        <a href="javascript:void(0)"
           @click="pack">打包</a>
      </div>
    </div>
    <div class="list_item">
      <div class="list_item_left">
        <div class="list_item_title">
          发布
        </div>
        <div class="list_item_desc2">
          <div>发布且审核通过后，用户可以在插件中心搜索及下载</div>
          <transition name="fade">
            <div v-if="publishInfo && publishInfo[pluginInfo.pid]">
              <Tooltip :content="`${publishStatus[String(publishInfo[pluginInfo.pid].status)]}: ${publishInfo[pluginInfo.pid].errmsg}`"
                       placement="top"
                       :max-width="320"
                       :transfer="true"
                       :disabled="publishInfo[pluginInfo.pid].status != -1">
                <Tag :color="tagColor"
                     type="border"
                     v-text="publishStatus[publishInfo[pluginInfo.pid].status]"></Tag>
              </Tooltip>

              <!-- v-text="publishInfo[pluginInfo.pid].url.split(SEP).pop()" -->
              插件: <a href="javascript:void(0)"
                 v-text="`${publishInfo[pluginInfo.pid].pluginName} @${publishInfo[pluginInfo.pid].version}`"
                 v-if="publishInfo[pluginInfo.pid].url"
                 style="margin-right: 4px;"
                 @click="openPublish"></a>最后发布于: <a href="javascript:void(0)"
                 @click="noop"
                 v-text="$timeFormat2(new Date(publishInfo[pluginInfo.pid].updatedAt).getTime())"></a>, 大小: <a href="javascript:void(0)"
                 @click="noop"
                 v-text="$sizeFormat(publishInfo[pluginInfo.pid].size)"></a>

            </div>
          </transition>
        </div>
      </div>
      <transition name="fade">
        <div class="list_item_right"
             v-if="progressInfo && progressInfo[pluginInfo.id] && (['success', 'fail'].indexOf(progressInfo[pluginInfo.id].step) < 0)">
          <img src="http://static.dei2.com/resources/loading.gif">
          <a href="javascript:void(0)"
             v-text="progressMap[progressInfo[pluginInfo.id].step]">
          </a>
        </div>
      </transition>
      <transition name="fade">
        <div class="list_item_right"
             v-if="!progressInfo || !progressInfo[pluginInfo.id] || (['success', 'fail'].indexOf(progressInfo[pluginInfo.id].step) > -1)">
          <a href="javascript:void(0)"
             @click="openPublishModal">
            发布
          </a>
        </div>
      </transition>

    </div>
    <div class="list_item no_border">
      <div class="list_item_left">
        <div class="list_item_title">
          删除
        </div>
        <div class="list_item_desc2">
          <div>删除插件后，将不可恢复</div>
        </div>
      </div>
      <div class="list_item_right">
        <a href="javascript:void(0)"
           style="color: #d33;"
           @click="del">删除</a>
      </div>
    </div>

    <Modal v-model="publishModal.shown"
           @on-ok="publish">
      <div slot="header"
           class="modal_title">
        提交审核
        <div class="modal_title_append"
             v-text="'【' + pluginInfo.pluginName + '@' + pluginInfo.version + '】'"></div>
      </div>
      <div class="modal_item">
        <div>是否覆盖审核中的版本</div>
        <i-switch v-model="publishModal.override">
          <span slot="open">是</span>
          <span slot="close">否</span>
        </i-switch>
      </div>
    </Modal>
  </div>
</template>

<script>
import { Switch, Button, Input, Select, Option, RadioGroup, Radio, Modal, Spin, Icon, Tag, Tooltip } from 'view-design'
import path from 'path'
import { createNamespacedHelpers, mapState } from 'vuex'
const { mapActions } = createNamespacedHelpers('./store/modules')
export default {
  name: 'TabManagement',
  components: {
    iSwitch: Switch,
    Button, Input, Select, Option, RadioGroup, Radio, Modal, Spin, Icon, Tag, Tooltip
  },
  props: {
    info: {
      type: Object,
      default () {
        return {}
      }
    },
    type: {
      type: String,
      default: ''
    }
  },
  watch: {
    info: {
      deep: true,
      immediate: true,
      handler (val) {
        this.initInfo()
      }
    }
  },
  data () {
    return {
      SEP: path.sep,
      debugTypes: [
        {
          name: 'file',
          label: '文件',
          placeholder: '/path/to/index.html',
          defaultValue: ''
        },
        {
          name: 'http',
          label: '服务',
          placeholder: 'http://127.0.0.1:8080',
          defaultValue: 'http://127.0.0.1:8080'
        }
      ],
      publishModal: {
        shown: false,
        override: false
      },
      currentType: 'file',
      pluginInfo: {},
      packInfo: {},
      publishInfo: {},
      progressInfo: {},
      progressMap: {
        pack: "打包中",
        upload: '上传中',
        submit: '提审中',
        success: '发布',
        fail: '发布'
      },
      publishStatus: {
        '0': '待审核',
        '1': '审核通过',
        '-1': '审核未通过'
      },
      viewStatus: {},
    }
  },
  computed: {
    ...mapState(
      {
        loginInfo: (state) => state.moduleUser.userInfo,
      }
    ),
    currentIndex () {
      if (this.currentType == 'file') {
        return 0
      } else {
        return 1
      }
    },
    rootPath () {
      if (!this.pluginInfo.local) return ''
      let _path = path.resolve(this.pluginInfo.local, '..')
      return _path
    },
    indexPath () {
      if (!this.pluginInfo.local) return ''
      let _path = path.resolve(this.pluginInfo.local, '..')
      return path.resolve(_path, this.pluginInfo.main || 'index.html')
    },
    needReload () {
      if (this.pluginInfo.debug?.type != this.info.debug?.type) {
        return true
      } else if (this.pluginInfo?.debug?.type == 'http') {
        return this.info.debug?.path != this.pluginInfo.debug?.path
      } else {
        return this.info.local != this.pluginInfo.local
      }
    },
    showPackInfo () {
      return this.packInfo && this.packInfo[this.pluginInfo.id] && this.packInfo[this.pluginInfo.id].path
    },
    tagColor () {
      let _status = this.publishInfo[this.pluginInfo.pid].status
      let outColor = ''
      switch (String(_status)) {
        case '0':
          // outColor = '#f90'
          outColor = '#2d8cf0'
          break
        case '1':
          outColor = '#19be6b'
          break
        case '-1':
          outColor = '#ed4014'
          break
        default:
          outColor = '#2d8cf0'
          break
      }
      return outColor
    }
  },
  created () {
    // this.initInfo()
  },
  mounted () {
    bbtools.on('plugin-pack-response', this.pluginPackResponse)
    bbtools.on('rfc-publish-response', this.rfcPublishResponse)
    bbtools.on('plugin-publish-progress', this.pluginPublishProgress)
    bbtools.on('rfc-info-response', this.rfcInfoResponse)
    // bbtools.on('rfc-view-response', this.rfcViewResponse)

  },
  methods: {
    rfcViewResponse (event, response) {
      if (response.action == 'done') {
        if (this.viewStatus[response.id]) {
          delete this.viewStatus[response.id]
        }
      } else {
        // console.log('#######', response)
        if (response.action == 'downloading') {
          this.$set(this.viewStatus, response.id, response.percent.toFixed(2) + '%')
        }
      }
    },
    initInfo () {
      this.pluginInfo = JSON.parse(JSON.stringify(this.info))
      this.currentType = this.pluginInfo.debug && this.pluginInfo.debug.type ? this.pluginInfo.debug.type : 'file'
      if (this.pluginInfo.id != 'bbtlovesyou') {
        // 获取插件的发布信息
        this.getRfcInfo()
      }
    },
    getRfcInfo () {
      bbtools.send('rfc-info', {
        pid: this.pluginInfo.pid,
        phonenum: this.loginInfo.phonenum,
        token: this.loginInfo.token
      })
      // if (responseInfo.status == 200) {
      //   this.$set(this.publishInfo, responseInfo.data.pid, responseInfo.data)
      // }
    },
    rfcInfoResponse (event, response) {
      if (response.code == 200) {
        this.$set(this.publishInfo, response.data.pid, response.data)
      }
    },
    noop (e) {
      e.preventDefault()
    },
    localPluginUpdate (params) {
      // bbtools.send('local-plugin-update', params)
      bbtools.send('plugin-reload', params)
    },
    changeDebugType (params) {
      this.pluginInfo.debug.type = params
    },
    changeIndexPath (e) {
      if (this.currentType == 'file') {
        this.validConf(e.target.value.trim()).then(() => {
          this.pluginInfo.local = e.target.value.trim()
          // this.localPluginUpdate(this.pluginInfo)
        }).catch(err => {
          this.$Message.error({
            content: err.message,
            duration: 5
          })

        })

      } else if (this.currentType == 'http') {
        this.pluginInfo.debug.path = e.target.value.trim()
        // this.localPluginUpdate(this.pluginInfo)
      }
    },
    validConf (dir) {
      return new Promise((resolve, reject) => {
        if (!bbtools.fs.existsSync(dir)) {
          reject(new Error('配置文件不存在'))
          return
        }
        let _conf = bbtools.fs.readFileSync(dir).toString()
        let _c
        try {
          _c = JSON.parse(_conf)
        } catch (err) {
          _c = {}
          reject(new Error(err.message))
          return
        }
        if (!bbtools.fs.existsSync(path.resolve(dir, '..', (_c.main || 'index.html')))) {
          reject(new Error('入口文件不存在'))
        } else {
          resolve(_c)
        }
      })
    },
    async chooseBBCFile () {
      let _p = bbtools.remote.dialog.showOpenDialogSync(bbtools.remote.getCurrentWindow(), {
        defaultPath: this.pluginInfo.local,
        properties: ['openFile'],
        filters: [
          {
            name: 'bbc', extensions: ['bbc']
          }
        ]
      })
      if (_p && _p.length > 0) {
        await this.validConf(_p[0]).then(conf => {
          this.pluginInfo.local = _p[0]
          this.localPluginUpdate(this.pluginInfo)
          this.$Message.success({
            content: '修改成功',
            duration: 5
          })
        }).catch(err => {
          this.$Message.error({
            content: err.message,
            duration: 5
          })
        })
      }
    },
    pageRefresh () {
      const that = this
      this.$Message.destroy()
      this.$Message.info({
        duration: 0,
        background: true,
        render: h => {
          return h('span', [
            '插件内容有更新，',
            h('a', {
              props: {
                href: ''
              },
              on: {
                click: () => {
                  that.$Message.destroy()
                  alert('刷新')
                }
              }
            }, '点击刷新')
          ])
        }
      })
    },
    pack (e) {
      e.preventDefault()
      bbtools.send('plugin-pack', this.info)
    },
    pluginPackResponse (event, response) {
      if (response.code == 200) {
        this.$set(this.packInfo, this.pluginInfo.id, response.data)
      }
    },
    openPack (e) {
      e.preventDefault()
      bbtools.shell.showItemInFolder(this.packInfo[this.pluginInfo.id].path)
    },
    openPublish (e) {
      e.preventDefault()
      let _p = this.publishInfo[this.pluginInfo.id].path
      if (_p) {
        bbtools.shell.showItemInFolder(this.publishInfo[this.pluginInfo.id].path)
      } else {
        _p = this.publishInfo[this.pluginInfo.id].url
        if (_p) {
          bbtools.send('rfc-view', this.publishInfo[this.pluginInfo.id])
        }
      }
    },
    openPublishModal () {
      this.publishModal.shown = true
    },
    publish (e) {
      bbtools.send('plugin-publish', Object.assign({}, this.pluginInfo, {
        override: this.publishModal.override,
        phonenum: this.loginInfo.phonenum
      }))
    },
    pluginPublishProgress (event, response) {
      this.$set(this.progressInfo, response.id, {
        step: response.step,
        message: response.message || ''
      })
    },
    rfcPublishResponse (event, response) {
      const that = this
      if (response.status == 401) {
        this.$Message.error({
          render: h => {
            return h('span', [
              '组件发布前请先',
              h('a', {
                href: '',
                style: {
                  marginLeft: '10px'
                },
                on: {
                  click: () => {
                    that.$Message.destroy()
                    eventBus.$emit('tab-change', {
                      name: 'Profile',
                      urlParams: {
                        action: 'login'
                      }
                    })
                  }
                }
              }, '去登录')
            ])
          },
          duration: 10
        })
      } else if (response.status == 200) {
        this.$set(this.publishInfo, response.data.pid, response.data)
        this.$Message.success({
          content: '已经提交审核',
          duration: 5
        })
      } else {
        this.$Message.error({
          content: response.message,
          duration: 5
        })
      }
    },
    del (e) {
      e.preventDefault()
      this.$Modal.confirm({
        title: '确认删除',
        content: '删除后无法恢复，请确认',
        cancelText: '取消',
        okText: '删除',
        onOk: () => {
          bbtools.send('plugin-remove', this.pluginInfo)
        }
      })
    },
    reloadPlugin (e) {
      e.preventDefault()
      if (this.pluginInfo.debug && this.pluginInfo.debug.type && (this.pluginInfo.debug.type == 'http') && this.pluginInfo.debug.path === '') {
        this.pluginInfo.debug.path = this.debugTypes[1].defaultValue
      }
      bbtools.send('plugin-reload', this.pluginInfo)
    }
  }
}
</script>

<style lang="less" scoped>
@import url("../../../themes/index.less");
.tab_container {
  width: 100%;
  height: 100%;
  padding: 15px;
  box-sizing: border-box;
  overflow-y: auto;
  .list_item {
    position: relative;
    width: 100%;
    border-bottom: 1px solid @darkDividerColor;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 10px 0;
    box-sizing: border-box;
    &.no_border {
      border-bottom: none !important;
    }
    &_left {
      flex: 1;
      height: 100%;
      display: flex;
      flex-direction: column;
      .list_item_title {
        width: 100%;
        height: 24px;
        color: @darkTextColor1;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-start;
      }
      .list_item_desc {
        width: 100%;
        margin-top: 10px;
        line-height: 1.5;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-start;
        font-size: 12px;
        color: @darkTextColor4;
      }
      .list_item_tip {
        font-size: 12px;
        margin-top: 5px;
        color: #f90;
      }
      .list_item_desc2 {
        width: 100%;
        margin-top: 10px;
        line-height: 1.5;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        font-size: 12px;
        color: @darkTextColor4;
      }
    }
    &_right {
      position: absolute;
      right: 0;
      min-width: 64px;
      height: 100%;
      margin-top: 15px;
      display: flex;
      flex-direction: row;
      align-items: flex-start;
      justify-content: flex-end;
      img {
        width: 16px;
        height: 16px;
        margin-top: 2px;
        margin-right: 4px;
      }
    }
  }
}
.modal_title {
  width: 100%;
  height: 20px;
  line-height: 20px;
  font-size: 16px;
  color: #17233d;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  &_append {
    // margin-left: 10px;
    color: green;
    font-weight: bold;
  }
}
.modal_item {
  width: 100%;
  height: 36px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
</style>